import wx
import wx.xrc as xrc
from wx.lib.mixins.listctrl import (
    ListCtrlAutoWidthMixin,
    ColumnSorterMixin,
    )

class myListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin, ColumnSorterMixin):

    def __init__(self, *args, **kwargs):
        super(myListCtrl, self).__init__(*args, **kwargs)
        ListCtrlAutoWidthMixin.__init__(self)
        ColumnSorterMixin.__init__(self, self.GetColumnCount())

    def GetListCtrl(self):
        return self

    def _columnSorter(self, key1, key2):
        _col = self._col
        _sf = self._colSortFlag[_col]
        _sf = 1 if _sf > 0 else -1
        _v1 = self.GetItem(key1, _col).GetText()
        _v2 = self.GetItem(key2, _col).GetText()
        return _sf * cmp(_v1, _v2)

    def GetColumnSorter(self):
	return self._columnSorter

    def InsertColumn(self, *args, **kw):
        super(myListCtrl, self).InsertColumn(*args, **kw)
        self.SetColumnCount(self.GetColumnCount())

    def DeleteColumn(self, *args, **kw):
        super(myListCtrl, self).DeleteColumn(*args, **kw)
        self.SetColumnCount(self.GetColumnCount())

class XrcHandler(xrc.XmlResourceHandler):
    extra_styles = [
        "LC_LIST",
        "LC_REPORT",
        "LC_VIRTUAL",
        "LC_ICON",
        "LC_SMALL_ICON",
        "LC_ALIGN_TOP",
        "LC_ALIGN_LEFT",
        "LC_AUTOARRANGE",
        "LC_EDIT_LABELS",
        "LC_NO_HEADER",
        "LC_SINGLE_SEL",
        "LC_SORT_ASCENDING",
        "LC_SORT_DESCENDING",
        "LC_HRULES",
        "LC_VRULES",
    ]

    def __init__(self):
        xrc.XmlResourceHandler.__init__(self)
        # Specify the styles recognized by objects of this type
        self.AddWindowStyles()
        for style in self.extra_styles:
            self.AddStyle("wx%s" % style, getattr(wx, style))

    # This method and the next one are required for XmlResourceHandlers
    def CanHandle(self, node):
        return \
            self.IsOfClass(node, "wxListCtrl") or \
            self.IsOfClass(node, "ListCtrl")

    def DoCreateResource(self):
        if self.GetInstance() is None:
            _ctrl = myListCtrl(
                self.GetParentAsWindow(),
                self.GetID(),
                self.GetPosition(),
                self.GetSize(),
                self.GetStyle(),
                name=self.GetName(),
            )
        else:
            _ctrl = self.GetInstance()
            _ctrl.Create(self.GetParentAsWindow(),
                 self.GetID(),
                 self.GetPosition(),
                 self.GetSize(),
                 self.GetStyle(),
                 name = self.GetName()
             )
        self.SetupWindow(_ctrl)
        self.CreateChildren(_ctrl)
        return _ctrl

# vim: set sts=4 sw=4 et :
